package com.maolong.spring.core.io;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import static cn.hutool.core.util.URLUtil.CLASSPATH_URL_PREFIX;

public class DefaultResourceLoader implements ResourceLoader{
    @Override
    public Resource getResource(String location) {
        if(location.startsWith(CLASSPATH_URL_PREFIX)){
            return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()));
        }else{
            try {
                URL url=new URL(location);
                return new UrlResource(url);
            } catch (MalformedURLException e) {
                return new FileSystemResource(location);
            }
        }
    }

    /**
     * 用来获取多个资源,个人想用来加载annotation时使用
     * @param location
     * @return
     */
    @Override
    public Resource[] getResources(String location) {
        List<Resource> resourceList = new ArrayList<>();
        try {
            ClassLoader classLoader = getClass().getClassLoader();
            Enumeration<URL> urls = classLoader.getResources(location);
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                if (url.getProtocol().equals("file")) {
                    // 如果是文件系统路径，使用 FileSystemResource
                    resourceList.add(new FileSystemResource(url.getFile()));
                }
                else {
                    // 默认使用 UrlResource
                    resourceList.add(new UrlResource(url));
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("加载资源失败: " + location, e);
        }
        return resourceList.toArray(new Resource[0]);
    }

}
